/*
 * Copyright 2007 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.sockets.applets.java;

import java.io.FilterInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Vector;

/**
 * This class provides asynchronous sockets functionality.
 * Checking stream is able to notify when exactly a socket has been closed and when data were received.
 *
 * @author Aleksey Lagoshin
 */
public class CheckingStream extends FilterInputStream {

  private static final int DEFAULT_BUFFER_SIZE = 8192;
  private static final int BUFFER_INCREASE = 1024;

  private int[] buffer;
  private int availableBytes = 0;

  private boolean capturing = false;
  private int capturedBytes;

  private Vector listeners;

  public CheckingStream(InputStream in) {
    super(in);
  }

  public CheckingStream(InputStream in, StreamListener listener) {
    super(in);
    addStreamListener(listener);
  }

  public void startReading() {
    buffer = new int[DEFAULT_BUFFER_SIZE];
    // Run method in a separate thread, so it won't block current thread
    new Thread(new Runnable() {
      public void run() {
        try {
          reading();
        }
        catch (IOException e) {
          System.out.println("Exception while waiting for data...");
          // Connection has been closed by an exception, that exception could be caused by closing current connection
          e.printStackTrace();
        }
        fireOnClose();
      }
    }, "BinaryReadingThread").start();
  }

  /**
   * The main loop. Reads bytes from a stream and puts them into buffer.
   *
   * @throws IOException on IO error
   */
  private void reading() throws IOException {
    int b = in.read();
    int loadedBytes = 1;
    while (b != -1) {
      synchronized (CheckingStream.this) {
        // Checking if we need to make buffer larger
        if (buffer.length == availableBytes) {
          int[] newBuffer = new int[buffer.length + BUFFER_INCREASE];
          System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
          buffer = newBuffer; 
        }
               
        buffer[availableBytes++] = b;

        // If there are no more bytes available in the stream we should notify stream listeners
        if (in.available() == 0) {
          fireOnData(loadedBytes);
          loadedBytes = 0;
        }
      }

      b = in.read();
      loadedBytes++;
    }
  }

  public int available() {
    return availableBytes;
  }

  public synchronized int read() throws IOException {
    if (availableBytes == 0)
      return -1;

    availableBytes--;

    int value;
    if (!capturing) {
      value = buffer[0];
      // Shift all elements left by one
      System.arraycopy(buffer, 1, buffer, 0, buffer.length-1);
    }
    else
      value = buffer[capturedBytes++];

    return value;
  }

  public synchronized int read(byte b[], int off, int len) throws IOException {
    if ((off | len | (off + len) | (b.length - (off + len))) < 0)
      throw new IndexOutOfBoundsException();
    else if (len == 0)
      return 0;

    boolean eof = false;
    if (len > availableBytes) {
      len = availableBytes;
      eof = true;
    }

    if (len != 0) {
      if (!capturing) {
        for (int i = 0; i < len; i++)
          b[i + off] = (byte) buffer[i];
        // Shift all elements left by len
        System.arraycopy(buffer, len, buffer, 0, buffer.length-len);
      }
      else {
        for (int i = 0; i < len; i++)
          b[i + off] = (byte) buffer[capturedBytes + i];
        capturedBytes += len;
      }

      availableBytes -= len;
    }

    return eof ? -1 : len;
  }

  public synchronized long skip(long n) throws IOException {
    if (n == 0)
      return 0;
    
    if (n > availableBytes)
      n = availableBytes;

    availableBytes -= n;
    // Shift all elements left by n
    System.arraycopy(buffer, (int) n, buffer, 0, buffer.length-(int) n);

    return n;
  }

  public void startCapturing() {
    if (capturing)
      return;
    capturing = true;
    capturedBytes = 0;
  }

  public void stopCapturing(boolean rollback) {
    if (!capturing)
      return;
    capturing = false;
    if (rollback)
      availableBytes += capturedBytes;
    else
      // Shift all elements left by one
      System.arraycopy(buffer, capturedBytes, buffer, 0, buffer.length-capturedBytes);
  }

  public void addStreamListener(StreamListener listener) {
    if (listeners == null)
      listeners = new Vector();

    listeners.add(listener);
  }

  public void removeStreamListener(StreamListener listener) {
    if (listeners != null)
      listeners.remove(listener);
  }

  private void fireOnData(int loadedBytes) {
    if (listeners != null)
      for (int i = 0; i < listeners.size(); i++)
        ((StreamListener) listeners.get(i)).onData(CheckingStream.this, loadedBytes);
  }

  private void fireOnClose() {
    if (listeners != null)
      for (int i = 0; i < listeners.size(); i++)
        ((StreamListener) listeners.get(i)).onClose(CheckingStream.this);
  }

}
